import 'package:bruno/bruno.dart';
import 'package:countdown/common/utils/utils.dart';
import 'package:countdown/common/values/values.dart';
import 'package:countdown/common/widgets/lottie.dart';
import 'package:countdown/common/widgets/widgets.dart';
import 'package:countdown/page/application/widget/SidebarMenu.dart';
import 'package:countdown/page/list/widget/ViewWidget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';
import 'package:reorderables/reorderables.dart';
import 'package:shrink_sidemenu/shrink_sidemenu.dart';
import '../../common/model/model.dart';
import '../../common/routers/names.dart';
import '../event/index.dart';
import 'index.dart';

///首页记账列表
class ListPage extends GetView<ListController> {
  const ListPage({super.key});

  @override
  Widget build(BuildContext context) {
    List<Widget> rows = [];
    bool isOpened = false;
    final GlobalKey<SideMenuState> sideMenuKey = GlobalKey<SideMenuState>();
    EventController eventController = Get.find();

    toggleMenu() {
      final state = sideMenuKey.currentState!;
      if (state.isOpened) {
        state.closeSideMenu();
      } else {
        state.openSideMenu();
      }
    }

    //拖动事件
    onReorder(int oldIndex, int newIndex) {
      Widget row = rows.removeAt(oldIndex);
      rows.insert(newIndex, row);
      //需要更新数据库sort
      controller.onReorder(oldIndex, newIndex);
    }

    BrnAppBar _buildAppBar() {
      return BrnAppBar(
          backgroundColor: AppColors.primaryBackground,
          //默认显示返回按钮
          automaticallyImplyLeading: false,
          //外部主题。状态栏颜色
          brightness: Brightness.light,
          leading: IconButton(
            onPressed: () async {
              toggleMenu();
            },
            icon: const Icon(
              Icons.menu_outlined,
              color: Colors.black,
            ),
          ),
          title: Text(
            "倒数时刻",
            style: TextStyle(
              color: AppColors.primaryText,
              fontFamily: 'Montserrat',
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
            ),
          ),
          actions: <Widget>[
            PopupMenu(
              secondaryButtonList: eventController.state.secondaryButtonList,
              secondaryButtonOnTap: (buttonPanelConfig) {
                eventController.state.buttonPanelConfig = buttonPanelConfig;
                Get.toNamed(AppRoutes.addEvent);
              },
              icon: const Icon(
                CupertinoIcons.add,
                color: AppColors.primaryText,
              ),
            ),
          ]);
    }

    ///左滑删除视觉
    Widget _buildChildItem(EventRecord eventRecord, int index) {
      //滑动组件MainAxisSize.min
      return Container(
          key: ValueKey(eventRecord.id),
          //m100, 300, 100, 300
          constraints: BoxConstraints(
              maxWidth: MediaQuery.of(context).size.width - 40.w,
              maxHeight: double.infinity,
              minHeight: 0,
              minWidth: 0),
          alignment: Alignment.center,
          margin: const EdgeInsets.only(left: 10, top: 4, bottom: 4, right: 10),
          child: Slidable(
            key: ValueKey(eventRecord.id),
            direction: Axis.horizontal,
            endActionPane: ActionPane(
                motion: const StretchMotion(),
                extentRatio: 0.6,
                children: [
                  SlidableAction(
                    flex: 3,
                    onPressed: (BuildContext context) {
                      List<BrnCommonActionSheetItem> actions = [];
                      actions.add(BrnCommonActionSheetItem(
                        '删除',
                        actionStyle: BrnCommonActionSheetItemStyle.alert,
                      ));

                      // 展示actionSheet
                      showModalBottomSheet(
                          context: context,
                          backgroundColor: Colors.transparent,
                          builder: (BuildContext context) {
                            return BrnCommonActionSheet(
                              title: "确认删除？",
                              actions: actions,
                              cancelTitle: "取消",
                              clickCallBack: (int index,
                                  BrnCommonActionSheetItem actionEle) {
                                controller.delete(eventRecord.id!);
                              },
                            );
                          });
                    },
                    backgroundColor: Color(0xFFFE4A49),
                    foregroundColor: Colors.white,
                    //icon: Icons.delete,
                    label: '删除',
                  ),
                  SlidableAction(
                    key: ValueKey(eventRecord.id),
                    flex: 3,
                    onPressed: (BuildContext context) {
                      EventRecord obj = eventRecord;
                      eventController.state.eventRecords = obj;
                      eventController.state.buttonPanelConfig =
                          ButtonPanelConfig(
                              name: eventController
                                  .state.lable[obj.type.toString()],
                              value: eventRecord.type,
                              emoji: eventRecord.emoji);
                      eventController.state.setInit(obj);
                      eventController.state.edit = true;
                      Get.toNamed(AppRoutes.addEvent);
                    },
                    label: "编辑",
                    backgroundColor: AppColors.primaryElement.withOpacity(0.8),
                    foregroundColor: Colors.white,
                    //icon: Icons.edit_calendar_outlined,
                  ),
                  SlidableAction(
                    flex: 3,
                    onPressed: (BuildContext context) {
                      if (index != 0) {
                        onReorder(index, 0);
                      }
                    },
                    backgroundColor: Colors.green.withOpacity(0.8),
                    foregroundColor: Colors.white,
                    //icon: Icons.upload_rounded,
                    label: "置顶",
                  ),
                ]),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                buildListTitle(eventRecord),
              ],
            ),
          ));
    }

    //创建可拖动组件
    Widget _buildReorderables() {
      rows = List.generate(controller.state.eventRecords.length, (index) {
        return _buildChildItem(controller.state.eventRecords[index], index);
      }).toList();

      return ReorderableListView(
        onReorder: onReorder,
        children: rows,
      );
    }

    return Scaffold(
      backgroundColor: AppColors.primaryBackground,
      appBar: _buildAppBar(),
      body: Obx(() => buildSideMenu(
            isOpened,
            sideMenuKey,
            controller.state.eventRecords == null ||
                    controller.state.eventRecords.length == 0
                ? loadingCat()
                : _buildReorderables(),
          )),
    );
  }
}
